package com.sunni.controller;

import com.sunni.entity.Customer;
import com.sunni.entity.Goods;
import com.sunni.mapper.moreToMore.CustomerMapper;
import com.sunni.mapper.moreToMore.GoodsMapper;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;

public class _03_03_多对多 {

 // 获取 这个**用户**，买了多少商品。（用户 里面，封装了List<商品>）
    @Test
    public void _03_多对多_查询顾客(){
        // 1. 读取mybatis核心文件
        InputStream inputStream =
                ResolverUtil.Test.class.getClassLoader().getResourceAsStream("config.xml");

        // 2.创建SqlSessionFactoryBuilder();
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        //  3.拿到sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

        //  4.开启SqlSession对话
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 5. SqlSession 获取 接口 get
        CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);

        //  6.accountMapper ：mapper对象执行 mapper层方法
        Customer customer = customerMapper.findById(1);
        System.out.println(customer.getId()+"--"+customer.getName());
        for (Goods goods : customer.getGoodsList()) {
            System.out.println(goods);
        }

        // 7.提交sql会话 （针对 增、删、改，能让数据库发生变化的使用commit）
        sqlSession.commit();

        //  8.关闭sql会话
        sqlSession.close();
    }


    @Test
    public void _03_多对多_查询商品(){
        // 1. 读取mybatis核心文件
        InputStream inputStream =
                ResolverUtil.Test.class.getClassLoader().getResourceAsStream("config.xml");

        // 2.创建SqlSessionFactoryBuilder();
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        //  3.拿到sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

        //  4.开启SqlSession对话
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 5. SqlSession 获取 接口 get
        GoodsMapper goodsMapper = sqlSession.getMapper(GoodsMapper.class);

        //  6.accountMapper ：mapper对象执行 mapper层方法
        Goods goods = goodsMapper.findById(2);
        System.out.println(goods.getId()+"--"+goods.getName());
        for (Customer customer : goods.getCustomerList()) {
            System.out.println(customer);
        }

        // 7.提交sql会话 （针对 增、删、改，能让数据库发生变化的使用commit）
        sqlSession.commit();

        //  8.关闭sql会话
        sqlSession.close();
    }

}
